package com.xing.config.ds.multi;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Bradish7Y on 2017/8/24.
 */
@Configuration
@ImportResource({"classpath:spring/spring-transaction-one.xml", "classpath:spring/spring-transaction-two.xml"})
public class MultiDataSourceConfig {

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 配置druid数据源，需配置，否则不生效
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource datasource_one() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /**
     * 配置druid数据源，需配置，否则不生效
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    public DataSource datasource_two() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

//    @Bean("dataSource")
//    @Order(99)
//    public DynamicDataSource dynamicDataSource(){
//        DynamicDataSource ds = new DynamicDataSource();
//        Map<Object, Object> sourceMap = new HashMap<>();
//        sourceMap.put("datasource_read", datasource_read());
//        sourceMap.put("datasource_write", datasource_write());
//        ds.setTargetDataSources(sourceMap);
//        ds.setDefaultTargetDataSource("datasource_write");
//
//        return  ds;
//    }

//    /**
//       * 单数据源，可以这样配置
//     * mybatis-plus分页插件<br>
//     * 文档：http://mp.baomidou.com<br>
//     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
//        return paginationInterceptor;
//    }

    @Bean
    public DataSourceTransactionManager oneTransactionManager() throws Exception {
        return new DataSourceTransactionManager(datasource_one());
    }

    @Bean
    public DataSourceTransactionManager twoTransactionManager() throws Exception {
        return new DataSourceTransactionManager(datasource_two());
    }
}
